<template>
  <view 
    class="trust-drag-card"
    :class="cardClasses"
    :draggable="draggable"
    @dragstart="handleDragStart"
    @dragend="handleDragEnd"
    @dragover="handleDragOver"
    @drop="handleDrop"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
  >
    <!-- 卡牌内容 -->
    <view class="card-content">
      <view class="card-header">
        <text class="card-title">{{ card.name }}</text>
        <view class="card-badges" v-if="card.badges && card.badges.length > 0">
          <view 
            class="badge" 
            v-for="badge in card.badges" 
            :key="badge.id"
            :class="badge.type"
          >
            <text class="badge-icon">{{ badge.icon }}</text>
          </view>
        </view>
      </view>
      
      <view class="card-body">
        <text class="card-description">{{ card.description }}</text>
        
        <!-- 信任值显示 -->
        <view class="trust-display">
          <text class="trust-label">信任值</text>
          <text class="trust-value">{{ card.trustValue }}</text>
          <view class="trust-progress">
            <view 
              class="progress-bar" 
              :style="{ width: card.trustValue + '%' }"
            ></view>
          </view>
        </view>
        
        <!-- 卡牌属性 -->
        <view class="card-attributes" v-if="card.attributes">
          <view 
            class="attribute-item" 
            v-for="(value, key) in card.attributes" 
            :key="key"
          >
            <text class="attribute-label">{{ key }}</text>
            <text class="attribute-value">{{ value }}</text>
          </view>
        </view>
      </view>
      
      <!-- 拖拽指示器 -->
      <view class="drag-indicator" v-if="isDragging">
        <text class="drag-icon">↕️</text>
        <text class="drag-text">拖拽中...</text>
      </view>
      
      <!-- 组合预览 -->
      <view class="combination-preview" v-if="showCombinationPreview">
        <text class="preview-title">组合效果</text>
        <view class="preview-effects">
          <view 
            class="effect-item" 
            v-for="effect in combinationEffects" 
            :key="effect.id"
          >
            <text class="effect-icon">{{ effect.icon }}</text>
            <text class="effect-text">{{ effect.description }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 拖拽目标区域 -->
    <view 
      class="drop-zone" 
      v-if="isDropTarget"
      :class="{ 'drop-active': isDropActive }"
    >
      <text class="drop-text">放置区域</text>
    </view>
    
    <!-- 组合结果 -->
    <view class="combination-result" v-if="combinationResult">
      <text class="result-title">组合成功！</text>
      <text class="result-description">{{ combinationResult.description }}</text>
      <view class="result-effects">
        <view 
          class="result-effect" 
          v-for="effect in combinationResult.effects" 
          :key="effect.id"
        >
          <text class="effect-icon">{{ effect.icon }}</text>
          <text class="effect-text">{{ effect.description }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import trustDragManager from '@/utils/trust-drag-manager.js'

export default {
  name: 'TrustDragCard',
  props: {
    card: {
      type: Object,
      required: true,
      default: () => ({
        id: 'default-card',
        name: '默认卡牌',
        description: '一张普通的信任卡牌',
        trustValue: 50,
        attributes: {},
        badges: []
      })
    },
    draggable: {
      type: Boolean,
      default: true
    },
    isDropTarget: {
      type: Boolean,
      default: false
    },
    combinationRules: {
      type: Array,
      default: () => []
    }
  },
  
  data() {
    return {
      isDragging: false,
      isDropActive: false,
      showCombinationPreview: false,
      combinationEffects: [],
      combinationResult: null,
      dragStartPosition: null,
      touchStartPosition: null,
      isTouchDragging: false
    }
  },
  
  computed: {
    cardClasses() {
      return {
        'dragging': this.isDragging,
        'drop-target': this.isDropTarget,
        'drop-active': this.isDropActive,
        'combination-preview': this.showCombinationPreview,
        'trust-high': this.card.trustValue >= 80,
        'trust-medium': this.card.trustValue >= 50 && this.card.trustValue < 80,
        'trust-low': this.card.trustValue < 50
      }
    }
  },
  
  methods: {
    // 拖拽开始
    handleDragStart(event) {
      if (!this.draggable) return
      
      this.isDragging = true
      this.dragStartPosition = {
        x: event.clientX,
        y: event.clientY
      }
      
      // 设置拖拽数据
      event.dataTransfer.setData('application/json', JSON.stringify({
        cardId: this.card.id,
        cardData: this.card,
        sourceElement: this.$el
      }))
      
      // 设置拖拽效果
      event.dataTransfer.effectAllowed = 'move'
      
      // 触发拖拽开始事件
      this.$emit('drag-start', {
        card: this.card,
        position: this.dragStartPosition
      })
      
      // 记录拖拽开始
      trustDragManager.recordDragStart(this.card.id, this.dragStartPosition)
    },
    
    // 拖拽结束
    handleDragEnd(event) {
      this.isDragging = false
      this.showCombinationPreview = false
      this.combinationEffects = []
      
      // 触发拖拽结束事件
      this.$emit('drag-end', {
        card: this.card,
        success: event.dataTransfer.dropEffect === 'move'
      })
      
      // 记录拖拽结束
      trustDragManager.recordDragEnd(this.card.id, event.dataTransfer.dropEffect === 'move')
    },
    
    // 拖拽悬停
    handleDragOver(event) {
      if (!this.isDropTarget) return
      
      event.preventDefault()
      event.dataTransfer.dropEffect = 'move'
      
      this.isDropActive = true
      
      // 检查组合可能性
      this.checkCombinationPossibility(event)
    },
    
    // 拖拽放置
    handleDrop(event) {
      if (!this.isDropTarget) return
      
      event.preventDefault()
      this.isDropActive = false
      
      try {
        const dragData = JSON.parse(event.dataTransfer.getData('application/json'))
        
        if (dragData.cardId && dragData.cardId !== this.card.id) {
          // 尝试组合
          this.attemptCombination(dragData.cardData, this.card)
        }
      } catch (error) {
        console.error('Failed to parse drag data:', error)
      }
    },
    
    // 触摸开始
    handleTouchStart(event) {
      if (!this.draggable) return
      
      this.touchStartPosition = {
        x: event.touches[0].clientX,
        y: event.touches[0].clientY
      }
      
      this.isTouchDragging = false
    },
    
    // 触摸移动
    handleTouchMove(event) {
      if (!this.draggable || !this.touchStartPosition) return
      
      const currentPosition = {
        x: event.touches[0].clientX,
        y: event.touches[0].clientY
      }
      
      const distance = Math.sqrt(
        Math.pow(currentPosition.x - this.touchStartPosition.x, 2) +
        Math.pow(currentPosition.y - this.touchStartPosition.y, 2)
      )
      
      if (distance > 10 && !this.isTouchDragging) {
        this.isTouchDragging = true
        this.isDragging = true
        
        // 触发触摸拖拽开始
        this.$emit('touch-drag-start', {
          card: this.card,
          position: this.touchStartPosition
        })
      }
      
      if (this.isTouchDragging) {
        // 更新拖拽位置
        this.$emit('touch-drag-move', {
          card: this.card,
          position: currentPosition
        })
      }
    },
    
    // 触摸结束
    handleTouchEnd(event) {
      if (this.isTouchDragging) {
        this.isTouchDragging = false
        this.isDragging = false
        
        // 触发触摸拖拽结束
        this.$emit('touch-drag-end', {
          card: this.card,
          position: {
            x: event.changedTouches[0].clientX,
            y: event.changedTouches[0].clientY
          }
        })
      }
      
      this.touchStartPosition = null
    },
    
    // 检查组合可能性
    checkCombinationPossibility(event) {
      try {
        const dragData = JSON.parse(event.dataTransfer.getData('application/json'))
        
        if (dragData.cardId && dragData.cardId !== this.card.id) {
          const effects = this.calculateCombinationEffects(dragData.cardData, this.card)
          
          if (effects.length > 0) {
            this.showCombinationPreview = true
            this.combinationEffects = effects
          }
        }
      } catch (error) {
        console.error('Failed to check combination:', error)
      }
    },
    
    // 计算组合效果
    calculateCombinationEffects(card1, card2) {
      const effects = []
      
      // 基础信任值组合
      const combinedTrust = Math.min(100, card1.trustValue + card2.trustValue)
      if (combinedTrust > card1.trustValue) {
        effects.push({
          id: 'trust_boost',
          icon: '📈',
          description: `信任值提升至 ${combinedTrust}`
        })
      }
      
      // 属性组合
      if (card1.attributes && card2.attributes) {
        const combinedAttributes = { ...card1.attributes, ...card2.attributes }
        Object.keys(combinedAttributes).forEach(key => {
          if (card1.attributes[key] && card2.attributes[key]) {
            effects.push({
              id: `attribute_${key}`,
              icon: '⚡',
              description: `${key} 属性增强`
            })
          }
        })
      }
      
      // 特殊组合规则
      this.combinationRules.forEach(rule => {
        if (rule.matches(card1, card2)) {
          effects.push({
            id: rule.id,
            icon: rule.icon,
            description: rule.description
          })
        }
      })
      
      return effects
    },
    
    // 尝试组合
    attemptCombination(card1, card2) {
      const effects = this.calculateCombinationEffects(card1, card2)
      
      if (effects.length > 0) {
        // 创建组合结果
        this.combinationResult = {
          description: `成功组合 ${card1.name} 和 ${card2.name}`,
          effects: effects
        }
        
        // 触发组合成功事件
        this.$emit('combination-success', {
          card1: card1,
          card2: card2,
          effects: effects
        })
        
        // 记录组合
        trustDragManager.recordCombination(card1.id, card2.id, effects)
        
        // 显示结果动画
        this.showCombinationResult()
      } else {
        // 组合失败
        this.$emit('combination-failed', {
          card1: card1,
          card2: card2,
          reason: '无法组合'
        })
      }
    },
    
    // 显示组合结果
    showCombinationResult() {
      // 显示结果动画
      setTimeout(() => {
        this.combinationResult = null
        this.showCombinationPreview = false
        this.combinationEffects = []
      }, 3000)
    },
    
    // 重置组合状态
    resetCombination() {
      this.showCombinationPreview = false
      this.combinationEffects = []
      this.combinationResult = null
      this.isDropActive = false
    }
  },
  
  mounted() {
    // 注册拖拽事件监听器
    if (this.isDropTarget) {
      this.$el.addEventListener('dragover', this.handleDragOver)
      this.$el.addEventListener('drop', this.handleDrop)
    }
  },
  
  beforeDestroy() {
    // 清理事件监听器
    if (this.isDropTarget) {
      this.$el.removeEventListener('dragover', this.handleDragOver)
      this.$el.removeEventListener('drop', this.handleDrop)
    }
  }
}
</script>

<style scoped>
.trust-drag-card {
  background: white;
  border-radius: 20rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: grab;
  position: relative;
  border: 2rpx solid #e0e0e0;
  user-select: none;
}

.trust-drag-card:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.15);
}

.trust-drag-card.dragging {
  opacity: 0.7;
  transform: rotate(5deg) scale(1.05);
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

.trust-drag-card.drop-target {
  border-style: dashed;
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.trust-drag-card.drop-active {
  border-color: #4caf50;
  background: rgba(76, 175, 80, 0.1);
  transform: scale(1.02);
}

.trust-drag-card.combination-preview {
  border-color: #ff9800;
  background: rgba(255, 152, 0, 0.1);
}

.trust-drag-card.trust-high {
  border-color: #4caf50;
  background: linear-gradient(135deg, #e8f5e8 0%, #f1f8e9 100%);
}

.trust-drag-card.trust-medium {
  border-color: #ff9800;
  background: linear-gradient(135deg, #fff3e0 0%, #fff8e1 100%);
}

.trust-drag-card.trust-low {
  border-color: #f44336;
  background: linear-gradient(135deg, #ffebee 0%, #fce4ec 100%);
}

/* 卡牌内容 */
.card-content {
  position: relative;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.card-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.card-badges {
  display: flex;
  gap: 8rpx;
}

.badge {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16rpx;
}

.badge.achievement {
  background: #4caf50;
  color: white;
}

.badge.special {
  background: #ff9800;
  color: white;
}

.badge.vip {
  background: #9c27b0;
  color: white;
}

.badge-icon {
  font-size: 14rpx;
}

.card-body {
  margin-bottom: 16rpx;
}

.card-description {
  font-size: 22rpx;
  color: #666;
  line-height: 1.4;
  margin-bottom: 16rpx;
  display: block;
}

/* 信任值显示 */
.trust-display {
  margin-bottom: 16rpx;
}

.trust-label {
  font-size: 18rpx;
  color: #666;
  display: block;
  margin-bottom: 6rpx;
}

.trust-value {
  font-size: 24rpx;
  font-weight: bold;
  color: #667eea;
  display: block;
  margin-bottom: 8rpx;
}

.trust-progress {
  width: 100%;
  height: 6rpx;
  background: #e0e0e0;
  border-radius: 3rpx;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #4caf50, #8bc34a);
  border-radius: 3rpx;
  transition: width 0.3s ease;
}

/* 卡牌属性 */
.card-attributes {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.attribute-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6rpx 12rpx;
  background: #f8f9fa;
  border-radius: 6rpx;
}

.attribute-label {
  font-size: 18rpx;
  color: #666;
}

.attribute-value {
  font-size: 18rpx;
  font-weight: bold;
  color: #333;
}

/* 拖拽指示器 */
.drag-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 12rpx 20rpx;
  border-radius: 12rpx;
  text-align: center;
  z-index: 1001;
  animation: dragPulse 1s infinite;
}

.drag-icon {
  font-size: 24rpx;
  display: block;
  margin-bottom: 4rpx;
}

.drag-text {
  font-size: 16rpx;
}

@keyframes dragPulse {
  0%, 100% { opacity: 0.8; transform: translate(-50%, -50%) scale(1); }
  50% { opacity: 1; transform: translate(-50%, -50%) scale(1.05); }
}

/* 组合预览 */
.combination-preview {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: rgba(255, 152, 0, 0.95);
  color: white;
  padding: 16rpx;
  border-radius: 12rpx;
  margin-top: 8rpx;
  z-index: 1000;
  animation: previewSlideIn 0.3s ease-out;
}

.preview-title {
  font-size: 20rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 8rpx;
}

.preview-effects {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.effect-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.effect-icon {
  font-size: 16rpx;
}

.effect-text {
  font-size: 16rpx;
}

@keyframes previewSlideIn {
  0% {
    opacity: 0;
    transform: translateY(-10rpx);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 拖拽目标区域 */
.drop-zone {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(102, 126, 234, 0.1);
  border: 2rpx dashed #667eea;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.drop-zone.drop-active {
  opacity: 1;
  background: rgba(76, 175, 80, 0.1);
  border-color: #4caf50;
}

.drop-text {
  font-size: 24rpx;
  color: #667eea;
  font-weight: bold;
}

/* 组合结果 */
.combination-result {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: linear-gradient(135deg, #4caf50, #8bc34a);
  color: white;
  padding: 20rpx;
  border-radius: 16rpx;
  text-align: center;
  z-index: 1002;
  animation: resultBounce 0.6s ease-out;
  box-shadow: 0 8rpx 25rpx rgba(76, 175, 80, 0.3);
}

.result-title {
  font-size: 24rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 8rpx;
}

.result-description {
  font-size: 18rpx;
  opacity: 0.9;
  display: block;
  margin-bottom: 12rpx;
}

.result-effects {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.result-effect {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 16rpx;
}

@keyframes resultBounce {
  0% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.5);
  }
  50% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1.1);
  }
  100% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

/* 响应式设计 */
@media (max-width: 768rpx) {
  .trust-drag-card {
    padding: 20rpx;
    margin-bottom: 12rpx;
  }
  
  .card-title {
    font-size: 24rpx;
  }
  
  .card-description {
    font-size: 20rpx;
  }
  
  .trust-value {
    font-size: 20rpx;
  }
  
  .attribute-item {
    padding: 4rpx 8rpx;
  }
  
  .attribute-label,
  .attribute-value {
    font-size: 16rpx;
  }
}
</style>

